<?php

namespace Admin\Controller;

use User\Api\UserApi;
use Org\Util\Sync;
use Think\Model;
use Org\Util\Rest;
use Org\BMap; 

/**
 * 退单控制器
 * @author Scor
 * 2015-06-17
 */
class RejectController extends AdminController {
    /**
     * 获取退货单列表
     */
    public function rejectOrders(){
        $map=array();
        $isExport = I('isExport');
        $oid = I('oid');
        $tdorderid = I('tdorderid');
        $toName = I('toName');
        $toPhone = I('toPhone');
        $b_date = I('b_date');
        $e_date = I('e_date');
        if ($b_date && $e_date) {
            //$sql .= " and gr_order.createDate >= " . strtotime($b_date);
            $map['createtime']=array('between',array(strtotime($b_date),strtotime($e_date)));
        }else if($b_date){
            $map['createtime']=array('egt',strtotime($b_date));
        }else if($e_date) {
            //$sql .= " and gr_order.createDate <= " . strtotime($e_date);
            $map['createtime']=array('elt',strtotime($e_date));
        }

        if($isExport!=null&&$isExport!=""){
            $map['is_export'] = $isExport;
        }
        if($oid!=""){
            $map['oldorderid'] = array('LIKE','%'.$oid.'%') ;
        }
        if($tdorderid!=""){
            $map['tdorderid'] = array('LIKE','%'.$tdorderid.'%') ;
        }
        if($toName!=""){
            $map['toName'] = array('LIKE','%'.$toName.'%') ;
        }
        if($toPhone!=""){
            $map['toPhone'] = array('LIKE','%'.$toPhone.'%') ;
        }
        $rejectOrders = $this->listsM('reject', $map,'createtime desc');
        $this->assign('rejectOrders',$rejectOrders);
        $this->assign('_isExport', $isExport);
        $this->display();
    }
    public function detail(){
        $tdorderid=I('orderid');
        $tdinfo = M('reject')->where(array('tdorderid' => $tdorderid))->find();
        $rejectGoods = M('reject_goods')->where(array('tdorderid' => $tdorderid))->select();
        $this->tdGoods = $rejectGoods;
        $this->tdInfo = $tdinfo;
//        var_dump($tdinfo);
        $this->display();
    }
    /**
     * 新增退单保存
     */
    public function addRejectOrders(){
        if (IS_POST) {
            $oldorderid = I('oldorderid');
            $tdorderid = 'THD'.date("YmdHis");
            $pname_arry = I('tdpname');
            $tdmark = I('tdmark');
            $toName = I('toName');
            $toPhone = I('toPhone');
            $toStreet = I('toStreet');
            $tdtotalpricearray = I('tdtotalprice');
            $td_user_arr=I('td_user');
            $td_type_arr=I('td_type');
            $tdtotalprice=0;
            $flag=false;
            for ($i = 0; $i < count($pname_arry); $i++) {
                if ($pname_arry[$i] != ""&&$tdtotalpricearray[$i] != "") {
                    $flag=true;
                    $tdtotalprice+=$tdtotalpricearray[$i];
                }
            }
            if(!$flag){
                $this->error("商品信息内容不能为空");
            }
            $data = array('toName' => $toName,'toPhone' => $toPhone,'toStreet' => $toStreet,'tdorderid'=>$tdorderid,'tdtotalprice'=>$tdtotalprice,'oldorderid'=>$oldorderid,'tdmark'=>$tdmark,'tdtotalprice'=>$tdtotalprice,'createtime' => NOW_TIME,'updatetime' => NOW_TIME,'is_export'=>0);
            $res = M('reject')->add($data);
            if (!$res) {
                $this->error("受理失败！");
            } else {
                for ($i = 0; $i < count($pname_arry); $i++) {
                    if($pname_arry[$i] != ""&&$tdtotalpricearray[$i] != " "&&$tdtotalpricearray[$i] != 0){
                        $dataList[] = array(
                            'tdorderid' => $tdorderid,
                            'tdpname' => $pname_arry[$i],
                            'tdtotalprice' => $tdtotalpricearray[$i],
                            'td_user' => $td_user_arr[$i],
                            'td_type' => $td_type_arr[$i]
                        );
                    }
                }
                D('reject_goods')->addAll($dataList);
                $this->success('受理成功！', U('Reject/rejectOrders'));
            }
        } else {
            $this->error("受理失败！");
        }

    }
    /**
     * 退单编辑页面
     * @param string $orderid
     */
    public function dealWith($orderid=""){
        if($orderid!=""){
            $orderDetail = M('order')->where(array('orderid'=>$orderid))->find();
            $ordergoods = M('vorder_goods')->where(array('orderid'=>$orderid))->select();
//            var_dump($orderDetail);
            $this->orderDetail = $orderDetail;
            $this->assign('ordergoods',$ordergoods);
        }
        $this->display();
    }
    /**
     * 退单详情
     * @author Scor
     * 2015-06-18
     */
    public function Rejectdetails($orderid = null) {
        $map['orderid'] = $orderid;
        $orderlist = D('reject_order')->where($map)->select();
        sg_td_int_to_string_order($orderlist);
        $order = $orderlist[0];
        $order['order_goods'] =D('oderder')->query("select * from gr_reject_order_goods where orderid = '".$map['orderid']."'");
        $this->order = $order;
        
        $this->display();
    }
    /**
     * 删除订单
     * @param $orderid
     */
    public function ajaxRejectDel($tdorderid){
        $dataDel['tdorderid']=$tdorderid;
        if(D('reject')->where($dataDel)->delete()&&D('reject_goods')->where($dataDel)->delete()){
             $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }
    /**
     * 退单申请管理
     * @author by scor
     */
    public function reject(){
        $id = I('id');
        $status = I('status');
        $b_date = I('b_date');
        $e_date = I('e_date');
        if ($id) {
            $map['orderid']=array('like','%'.$id.'%');
        }
        if ($status != null && $status != 0) {
            $map['status']=$status;
        }
        if ($b_date && $e_date) {
            $map['createtime']=array('between',array(strtotime($b_date),strtotime($e_date)));
        }else if($b_date){
            $map['createtime']=array('egt',strtotime($b_date));
        }else if($e_date) {
            $map['createtime']=array('elt',strtotime($e_date));
        }
        $list = $this->listsM('reject_order', $map,'create_time desc');
        sg_td_int_to_string_order($list);
        $this->assign('_list', $list);
        $this->assign('_status', $status);
        $this->display();
    }
    /**
     * 退单导出
     */
    public function orderExport() {
        $sql = "select a.tdorderid,a.oldorderid,ABS(a.tdtotalprice),b.toName,a.tdmark,b.toPhone,b.toStreet,"
            ." from_unixtime(a.createtime),from_unixtime(b.createDate),"
            ."(select c.goods1 from gr_vreject_goods c where a.tdorderid = c.tdorderid)goods"
            ." from gr_reject a ,gr_order b where a.oldorderid = b.orderid";

        $isExport = I('isExport');
        $oid = I('oid');
        $tdorderid = I('tdorderid');
        $toName = I('toName');
        $toPhone = I('toPhone');
        $b_date = I('b_date');
        $e_date = I('e_date');
         if($b_date){
             $sql .= " and a.createtime >= " . strtotime($b_date);
        }
         if($e_date) {
             $sql .= " and a.createtime <= " . strtotime($e_date);
         }
        if ($oid) {
            $sql .= " and a.oid like '%" . $oid . "%'";
        }
        if ($tdorderid) {
            $sql .= " and a.tdorderid like '%" . $tdorderid . "%'";
        }
        if ($toName) {
            $sql .= " and a.toName like '%" . $toName . "%'";
        }
        if ($toPhone) {
            $sql .= " and a.toPhone like '%" . $toPhone . "%'";
        }
        if($isExport!=null&&$isExport!=""){
            $sql .= " and a.is_export = " . $isExport;
        }

//        if ($b_date) {
//            $sql .= " and a.createDate >= " . strtotime($b_date);
//        }
//        if ($e_date) {
//            $sql .= " and a.createDate <= " . strtotime($e_date);
//        }
        $Model = new Model();
        $data = $Model->query($sql);
        if ($data) {
            $orderTable = M('reject');
            $data1 = array('is_export' => 1);
            $args = array_map(function($src){
                return $src['tdorderid'];}, $data);
            $map['tdorderid']  = array('in',$args);
            $orderTable->where($map)->setField($data1);
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");
            $filename = "世果退单";
            $headArr = array("退单编号","原订单号","退单金额","收货人","退货备注","联系方式","收货地址","退单时间","下单时间","退货商品");
            $this->getExcel($filename, $headArr, $data,null);
        }else{
            $this->error("没有可导出的数据");
        }
    }
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("YmdHi", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);
        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $objPHPExcel->getActiveSheet()->getStyle($colum . '2')->getFont()->setBold(true);
            $key += 1;
        }
        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
        $objActSheet->getColumnDimension('A')->setWidth(20);
        $objActSheet->getColumnDimension('B')->setWidth(15);
        $objActSheet->getColumnDimension('C')->setWidth(10);
        $objActSheet->getColumnDimension('D')->setWidth(10);
        $objActSheet->getColumnDimension('E')->setWidth(30);
        $objActSheet->getColumnDimension('F')->setWidth(15);
        $objActSheet->getColumnDimension('G')->setWidth(20);
        $objActSheet->getColumnDimension('H')->setWidth(15);
        $objActSheet->getColumnDimension('I')->setWidth(15);
        $objActSheet->getColumnDimension('J')->setWidth(60);
        $objActSheet->getColumnDimension('K')->setWidth(30);

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

}
